from config import load_config
import math
from ticktock import Ticktock

class Marketing:
    def __init__(self, session_id, country, shop_id):
        self.sesson_id = session_id
        self.shop_id = shop_id
        self.country = country
        self.config = load_config(country)

    def format_price(self, price):
        if self.country == 'VN':
            return math.ceil(price)
        else:
            return math.ceil(price * 100) / 100

    def calculate_kill_price(self, price, weight, coupon_amount, country_config):
        try:
            # 从配置中获取公式和参数
            formula = country_config.get('formula')
            
            # 获取所有常量参数
            constants = {k: v for k, v in country_config.items() if k != 'formula'}
            # 替换公式中的变量和常量
            rmb_price = float(price)
            weight = float(weight)
            
            # 替换常量参数
            for key, value in constants.items():
                formula = formula.replace(f'{{{key}}}', str(value))
            
            # 替换变量
            formula = formula.replace('<<采集价>>', str(rmb_price))
            formula = formula.replace('<<克重>>', str(weight))
            formula = formula.replace('<<优惠券>>', str(coupon_amount))
            
            # 计算最终价格
            kill_price = eval(formula)
            
            return self.format_price(kill_price), formula
        except Exception as e:
            raise Exception(f"秒杀价计算失败，请检查公式: {str(e)}")

    def apply_marketing_plan(self, product, coupon_amount):
        price = product['price']
        if price == '' or price is None:
            rmb_price = 0
        else:
            rmb_price = float(price)
        weight = product.get('weight', 0)
        if weight == '':
            weight = 0
        weight = int(weight)
        if weight <= 0:
            product_info = Ticktock(self.sesson_id).get_tt_product_info(self.shop_id, product['global_item_id'])
            weight = int(float(product_info.get('package_weight', 0)) * 1000)


        max_sku_price = max([sku['sale_price'] for sku in product['skus']])

        kill_price, kill_price_formula = self.calculate_kill_price(rmb_price, weight, coupon_amount, self.config)
        
        max_sku_kill_rate = math.floor(((max_sku_price - kill_price)/max_sku_price) * 100)
        if self.country == 'VN':
            kill_rate = min(max_sku_kill_rate, 50)   # 越南秒杀折扣率不超过50
        else: 
            kill_rate = min(max_sku_kill_rate, 90)   # 其他国家秒杀折扣率不超过90
        discount = (max_sku_kill_rate - 1)
        for sku in product['skus']:
            price = sku['sale_price']
            is_promote_sku = sku.get('is_promote_sku', False)
            if not is_promote_sku:
                sku['kill_price'] = self.format_price(price * (100 - kill_rate)/100)
                sku['kill_rate'] = kill_rate
            
            if is_promote_sku:
                # 引流品8折
                sku['discount_rate'] = 80
            else:
                sku['discount_rate'] = min(discount, 80)
                
        # 更新product中的skus
        product['skus'] = product['skus']
        product['weight'] = weight
        product['coupon_fee'] = coupon_amount
        product['kill_price_formula'] = kill_price_formula
        product['kill_price'] = kill_price
        product['kill_rate_formula'] = f'({max_sku_price} - {kill_price})/{max_sku_price} = {(max_sku_price - kill_price)/max_sku_price}'
        product['max_sku_kill_rate'] = max_sku_kill_rate
        return product

